/*
 *    Copyright (c) 2018-2025, shenghua All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: shenghua
 */

package com.chen.base.module.redis.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.chen.base.module.redis.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author ChenJinLong
 * @since 2021/9/3 9:15
 */
@Component
@Slf4j
public class CacheServiceImpl implements CacheService {

	@Resource
	RedisTemplate<String, Object> redisTemplate;

	/**
	 * 指定缓存失效时间
	 *
	 * @param key  键
	 * @param time 时间(秒)
	 * @return
	 */
	@Override
	public boolean expire(String key, long time) {
		return expire(key, time, true);
	}

	@Override
	public boolean expire(String key, long time, boolean tenantFlag) {
		try {
			if (time > 0) {
				return doExpire(key, time, tenantFlag);
			}
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	private boolean doExpire(String key, long time, boolean tenantFlag) {
		redisTemplate.expire(key, time, TimeUnit.SECONDS);
		return true;
	}

	/**
	 * 根据key 获取过期时间
	 *
	 * @param key 键 不能为null
	 * @return 时间(秒) 返回0代表为永久有效
	 */
	@Override
	public Long getExpire(String key) {
		return getExpire(key, true);
	}

	@Override
	public Long getExpire(String key, boolean tenantFlag) {
		return doGetExpire(key, tenantFlag);
	}

	private Long doGetExpire(String key, boolean tenantFlag) {
		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
	}

	/**
	 * 判断key是否存在
	 *
	 * @param key 键
	 * @return true 存在 false不存在
	 */
	@Override
	public Boolean hasKey(String key) {
		return hasKey(key, true);
	}

	@Override
	public Boolean hasKey(String key, boolean tenantFlag) {
		try {
			return doCheckHasKey(key, tenantFlag);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	private Boolean doCheckHasKey(String key, boolean tenantFlag) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 删除缓存
	 *
	 * @param key 可以传一个值 或多个
	 */
	@Override
	public void del(String... key) {
		del(true, key);
	}

	@Override
	public void del(boolean tenantFlag, String... key) {

		if (key != null && key.length > 0) {
			doDel(tenantFlag, key);
		}
	}

	private void doDel(boolean tenantFlag, String[] keys) {
		if (tenantFlag && keys != null && keys.length > 0) {
			if (keys.length == 1) {
				redisTemplate.delete(keys[0]);
				return;
			}

			List<String> keyList = new ArrayList<>(CollectionUtil.toList(keys));
			redisTemplate.delete(keyList);
			return;
		}

		if (keys != null && keys.length > 0) {
			if (keys.length == 1) {
				redisTemplate.delete(keys[0]);
				return;
			}

			redisTemplate.delete(Arrays.asList(keys));
		}
	}

	//============================String=============================

	/**
	 * 普通缓存获取
	 *
	 * @param key 键
	 * @return 值
	 */
	@Override
	public Object get(String key) {
		return get(key, true);
	}

	@Override
	public Object get(String key, boolean tenantFlag) {
		if (key == null) {
			return null;
		}

		return doGet(key, tenantFlag);
	}

	private Object doGet(String key, boolean tenantFlag) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 普通缓存放入
	 *
	 * @param key   键
	 * @param value 值
	 * @return true成功 false失败
	 */
	@Override
	public boolean set(String key, Object value) {
		return set(key, value, true);

	}

	@Override
	public boolean set(String key, Object value, boolean tenantFlag) {
		try {
			redisTemplate.opsForValue().set(key, value);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 普通缓存放入并设置时间
	 *
	 * @param key   键
	 * @param value 值
	 * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
	 * @return true成功 false 失败
	 */
	@Override
	public boolean set(String key, Object value, long time) {
		return set(key, value, time, true);
	}

	@Override
	public boolean set(String key, Object value, long time, boolean tenantFlag) {
		try {
			if (time > 0) {
				doSet(key, value, time, tenantFlag);
			} else {
				set(key, value);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private void doSet(String key, Object value, long time, boolean tenantFlag) {
		Assert.notNull(key);
		redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
	}

	/**
	 * 递增
	 *
	 * @param key   键
	 * @param delta 要增加几(大于0)
	 * @return
	 */
	@Override
	public Long incr(String key, long delta) {
		return incr(key, delta, true);
	}

	@Override
	public Long incr(String key, long delta, boolean tenantFlag) {
		Assert.notNull(key);
		if (delta < 0) {
			throw new IllegalArgumentException("递增因子必须大于0");
		}
		return redisTemplate.opsForValue().increment(key, delta);
	}

	/**
	 * 递减
	 *
	 * @param key   键
	 * @param delta 要减少几(小于0)
	 * @return
	 */
	@Override
	public Long decr(String key, long delta) {
		return decr(key, delta, true);
	}

	@Override
	public Long decr(String key, long delta, boolean tenantFlag) {
		Assert.notNull(key);
		if (delta < 0) {
			throw new IllegalArgumentException("递减因子必须大于0");
		}
		try {
			return redisTemplate.opsForValue().increment(key, -delta);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}

	//================================Map=================================

	/**
	 * HashGet
	 *
	 * @param key  键 不能为null
	 * @param item 项 不能为null
	 * @return 值
	 */
	@Override
	public Object hget(String key, String item) {
		return hget(key, item, true);
	}

	@Override
	public Object hget(String key, String item, boolean tenantFlag) {
		if (key == null) {
			return null;
		}
		return redisTemplate.opsForHash().get(key, item);
	}

	/**
	 * 获取hashKey对应的所有键值
	 *
	 * @param key 键
	 * @return 对应的多个键值
	 */
	@Override
	public Map<Object, Object> hmget(String key) {

		return hmget(key, true);
	}

	@Override
	public Map<Object, Object> hmget(String key, boolean tenantFlag) {
		if (key == null) {
			return null;
		}
		return redisTemplate.opsForHash().entries(key);
	}

	/**
	 * HashSet
	 *
	 * @param key 键
	 * @param map 对应多个键值
	 * @return true 成功 false 失败
	 */
	@Override
	public boolean hmset(String key, Map<String, Object> map) {


		return hmset(key, map, true);
	}

	@Override
	public boolean hmset(String key, Map<String, Object> map, boolean tenantFlag) {
		Assert.notNull(key);
		try {
			redisTemplate.opsForHash().putAll(key, map);
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));

			return false;
		}
	}

	/**
	 * HashSet 并设置时间
	 *
	 * @param key  键
	 * @param map  对应多个键值
	 * @param time 时间(秒)
	 * @return true成功 false失败
	 */
	@Override
	public boolean hmset(String key, Map<String, Object> map, long time) {
		return hmset(key, map, time, true);
	}

	@Override
	public boolean hmset(String key, Map<String, Object> map, long time, boolean tenantFlag) {
		Assert.notNull(key);
		try {
			redisTemplate.opsForHash().putAll(key, map);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 向一张hash表中放入数据,如果不存在将创建
	 *
	 * @param key   键
	 * @param item  项
	 * @param value 值
	 * @return true 成功 false失败
	 */
	@Override
	public boolean hset(String key, String item, Object value) {
		return hset(key, item, value, true);
	}

	@Override
	public boolean hset(String key, String item, Object value, boolean tenantFlag) {
		Assert.notNull(key);
		try {
			redisTemplate.opsForHash().put(key, item, value);
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 向一张hash表中放入数据,如果不存在将创建
	 *
	 * @param key   键
	 * @param item  项
	 * @param value 值
	 * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
	 * @return true 成功 false失败
	 */
	@Override
	public boolean hset(String key, String item, Object value, long time) {
		return hset(key, item, value, time, true);
	}

	@Override
	public boolean hset(String key, String item, Object value, long time, boolean tenantFlag) {
		Assert.notNull(key);
		try {
			redisTemplate.opsForHash().put(key, item, value);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 删除hash表中的值
	 *
	 * @param key  键 不能为null
	 * @param item 项 可以使多个 不能为null
	 */
	@Override
	public void hdel(String key, Object... item) {
		hdel(true, key, item);
	}

	@Override
	public void hdel(boolean tenantFlag, String key, Object... item) {
		Assert.notNull(key);
		redisTemplate.opsForHash().delete(key, item);
	}

	/**
	 * 判断hash表中是否有该项的值
	 *
	 * @param key  键 不能为null
	 * @param item 项 不能为null
	 * @return true 存在 false不存在
	 */
	@Override
	public boolean hHasKey(String key, String item) {
		return hHasKey(key, item, true);
	}

	@Override
	public boolean hHasKey(String key, String item, boolean tenantFlag) {
		Assert.notNull(key);
		return redisTemplate.opsForHash().hasKey(key, item);

	}

	/**
	 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
	 *
	 * @param key  键
	 * @param item 项
	 * @param by   要增加几(大于0)
	 * @return
	 */
	@Override
	public double hincr(String key, String item, double by) {
		return hincr(key, item, by, true);
	}

	@Override
	public double hincr(String key, String item, double by, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		return redisTemplate.opsForHash().increment(key, item, by);
	}

	/**
	 * hash递减
	 *
	 * @param key  键
	 * @param item 项
	 * @param by   要减少记(小于0)
	 * @return
	 */
	@Override
	public double hdecr(String key, String item, double by) {
		return hdecr(key, item, by, true);
	}

	@Override
	public double hdecr(String key, String item, double by, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		return redisTemplate.opsForHash().increment(key, item, -by);
	}

	//============================set=============================

	/**
	 * 根据key获取Set中的所有值
	 *
	 * @param key 键
	 * @return
	 */
	@Override
	public Set<Object> sGet(String key) {
		return sGet(key, true);
	}

	@Override
	public Set<Object> sGet(String key, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForSet().members(key);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return null;
		}
	}

	/**
	 * 根据value从一个set中查询,是否存在
	 *
	 * @param key   键
	 * @param value 值
	 * @return true 存在 false不存在
	 */
	@Override
	public Boolean sHasKey(String key, Object value) {
		return sHasKey(key, value, true);
	}

	@Override
	public Boolean sHasKey(String key, Object value, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForSet().isMember(key, value);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 将数据放入set缓存
	 *
	 * @param key    键
	 * @param values 值 可以是多个
	 * @return 成功个数
	 */
	@Override
	public Long sSet(String key, Object... values) {
		return sSet(true, key, values);
	}

	@Override
	public Long sSet(boolean tenantFlag, String key, Object... values) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForSet().add(key, values);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}

	/**
	 * 将set数据放入缓存
	 *
	 * @param key    键
	 * @param time   时间(秒)
	 * @param values 值 可以是多个
	 * @return 成功个数
	 */
	@Override
	public Long sSetAndTime(String key, long time, Object... values) {
		return sSetAndTime(true, key, time, values);
	}

	@Override
	public Long sSetAndTime(boolean tenantFlag, String key, long time, Object... values) {
		key = getKey(key, tenantFlag);
		try {
			Long count = redisTemplate.opsForSet().add(key, values);
			if (time > 0) {
				expire(key, time);
			}
			return count;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}

	/**
	 * 获取set缓存的长度
	 *
	 * @param key 键
	 * @return
	 */
	@Override
	public Long sGetSetSize(String key) {
		return sGetSetSize(key, true);
	}

	@Override
	public Long sGetSetSize(String key, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForSet().size(key);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}

	@Override
	public List sPop(String key, Integer count) {
		if (StringUtils.isEmpty(key) || count <= 0) {
			throw new IllegalArgumentException("参数错误！");
		}
		SetOperations<String, Object> opsForSet = redisTemplate.opsForSet();
		try {
			
			return opsForSet.pop(key, count);
		} catch (Exception e) {
			log.error(e.toString());
		}

		return new ArrayList<>();
	}

	@Override
	public Long sSize(String key) {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("参数错误！");
		}

		return redisTemplate.opsForSet().size(key);
	}

	/**
	 * 移除值为value的
	 *
	 * @param key    键
	 * @param values 值 可以是多个
	 * @return 移除的个数
	 */
	@Override
	public long setRemove(String key, Object... values) {
		return setRemove(true, key, values);
	}

	@Override
	public Long setRemove(boolean tenantFlag, String key, Object... values) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForSet().remove(key, values);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}
	//===============================list=================================

	/**
	 * 获取缓存中list所有的数据
	 * @param key key
	 * @param tClass 数据类对象
	 * @return 数据集
	 * @param <T> T
	 */
	@Override
	public <T> List<T> lGetAll(String key, Class<T> tClass){
		List<Object> objectList = lGet(key, 0, -1);
		if (objectList == null || objectList.size() == 0){
			return new ArrayList<>();
		}

		return (List<T>) objectList;
	}

	/**
	 * 获取list缓存的内容
	 *
	 * @param key   键
	 * @param start 开始
	 * @param end   结束  0 到 -1代表所有值
	 * @return list obj
	 */
	@Override
	public List<Object> lGet(String key, long start, long end) {
		return lGet(key, start, end, true);
	}

	@Override
	public List<Object> lGet(String key, long start, long end, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForList().range(key, start, end);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return null;
		}
	}

	/**
	 * 获取list缓存的长度
	 *
	 * @param key 键
	 * @return size
	 */
	@Override
	public long lGetListSize(String key) {
		return lGetListSize(key, true);
	}

	@Override
	public Long lGetListSize(String key, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForList().size(key);
		} catch (Exception e) {
			e.printStackTrace();
			return 0L;
		}
	}

	/**
	 * 通过索引 获取list中的值
	 *
	 * @param key   键
	 * @param index 索引  index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
	 * @return obj
	 */
	@Override
	public Object lGetIndex(String key, long index) {
		return lGetIndex(key, index, true);
	}

	@Override
	public Object lGetIndex(String key, long index, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForList().index(key, index);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return null;
		}
	}

	/**
	 * 将list放入缓存
	 *
	 * @param key   键
	 * @param value 值
	 * @return flag
	 */
	@Override
	public boolean lSet(String key, Object value) {
		return lSet(key, value, true);
	}

	@Override
	public boolean lSet(String key, Object value, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			redisTemplate.opsForList().rightPush(key, value);
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 将list放入缓存
	 *
	 * @param key   键
	 * @param value 值
	 * @param time  时间(秒)
	 * @return flag
	 */
	@Override
	public boolean lSet(String key, Object value, long time) {

		return lSet(key, value, time, true);
	}

	@Override
	public boolean lSet(String key, Object value, long time, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			redisTemplate.opsForList().rightPush(key, value);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 将list放入缓存
	 *
	 * @param key   键
	 * @param value 值
	 * @return flag
	 */
	@Override
	public boolean lSet(String key, List<Object> value) {
		return lSet(key, value, true);
	}

	@Override
	public boolean lSet(String key, List<Object> value, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			redisTemplate.opsForList().rightPushAll(key, value);
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 将list放入缓存
	 *
	 * @param key   键
	 * @param value 值
	 * @param time  时间(秒)
	 * @return flag
	 */
	@Override
	public boolean lSet(String key, List<Object> value, long time) {
		return lSet(key, value, time, true);
	}

	@Override
	public boolean lSet(String key, List<Object> value, long time, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			redisTemplate.opsForList().rightPushAll(key, value);
			if (time > 0) {
				expire(key, time);
			}
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 根据索引修改list中的某条数据
	 *
	 * @param key   键
	 * @param index 索引
	 * @param value 值
	 * @return flag
	 */
	@Override
	public boolean lUpdateIndex(String key, long index, Object value) {
		return lUpdateIndex(key, index, value, true);
	}

	@Override
	public boolean lUpdateIndex(String key, long index, Object value, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			redisTemplate.opsForList().set(key, index, value);
			return true;
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return false;
		}
	}

	/**
	 * 移除N个值为value
	 *
	 * @param key   键
	 * @param count 移除多少个
	 * @param value 值
	 * @return 移除的个数
	 */
	@Override
	public long lRemove(String key, long count, Object value) {
		return lRemove(key, count, value, true);

	}

	@Override
	public Long lRemove(String key, long count, Object value, boolean tenantFlag) {
		key = getKey(key, tenantFlag);
		try {
			return redisTemplate.opsForList().remove(key, count, value);
		} catch (Exception e) {
			log.error(String.valueOf(e));
			return 0L;
		}
	}


	private String getKey(String key, boolean tenantFlag) {
		Assert.notNull(key);
		return key;
	}

}
